<div class="modal-header">
    <button type="button" class="close" data-dismiss="modal" aria-hidden="true">&times;</button>
    <h4 class="modal-title">添加角色</h4>
</div>
<form id="defaultForm" method="post" class="form-horizontal" action="/system/user_save">
    <div class="modal-body">
        <input style="display: none" name="id" th:value="${user.id}">
        <div class="form-group">
            <label class="col-lg-3 control-label">用户名</label>
            <div class="col-lg-5">
                <input type="text" class="form-control" name="loginName" th:value="${user.loginName}"/>
            </div>
        </div>

        <div class="form-group">
            <label class="col-lg-3 control-label">登录密码</label>
            <div class="col-lg-5">
                <input type="text" class="form-control" name="password"  th:value="${user.password}"/>
            </div>
        </div>

        <div class="form-group">
            <label class="col-lg-3 control-label">确认密码</label>
            <div class="col-lg-5">
                <input type="text" class="form-control" name="checkPassword"  th:value="${user.password}"/>
            </div>
        </div>

        <div class="form-group" th:if="${parameter.id eq nowUser.role.type.id}">
            <label class="col-lg-3 control-label">修改口令</label>
            <div class="col-lg-5">
                <input type="text" class="form-control" name="changePassword"  th:value="${user.changePassword}"/>
            </div>
        </div>

        <div class="form-group">
            <label class="col-lg-3 control-label">角色</label>
            <div class="col-lg-5">
                <select class="form-control" name="role">
                    <option value="">选择角色</option>
                    <option th:each="role:${roles}" th:value="${role.id}" th:text="${role.name}" th:selected="${role.id == user.role.id}"></option>
                </select>
            </div>
        </div>

        <div class="form-group">
            <label class="col-lg-3 control-label">权限内项目</label>
            <div class="col-lg-5">
                <select id="object" name="object"  class="multiselect form-control" multiple="multiple" >
                    <!--<option th:each="project:${projectManages}" th:value="${project.id}" th:text="${project.name}"></option>-->
                </select>
            </div>
        </div>

    </div>
    <div class="modal-footer">
        <button type="button" class="btn btn-default" data-dismiss="modal">关闭</button>
        <button type="submit" class="btn btn-primary">保存</button>
    </div>
</form>

<script th:inline="javascript">
    //表单初始化
    initCheck();
    //添加验证
    $("#defaultForm").bootstrapValidator('addField','role',{
        validators: {
            notEmpty: {
                message: '角色不能为空'
            }
        }
    });

    var value=[];
    $(document).ready(function() {
        var userProjects=[[${userProjects}]];
        var projectManages=[[${projectManages}]];


        $("#object").empty();

        for (var i = 0; i < userProjects.length; i++) {
            value.push(userProjects[i].projectId.id);
            $(".multiselect").append("<option selected value='" + userProjects[i].projectId.id + "'>" + userProjects[i].projectId.name + "</option>");
            console.log(value);
        }

        for (var i = 0; i < projectManages.length; i++) {
            if( isInArray(value,projectManages[i].id)){
                console.log(projectManages[i]);

            }else{
                console.log(projectManages[i]);
                $(".multiselect").append("<option value='" + projectManages[i].id + "'>" + projectManages[i].name + "</option>");
            }
        }

        /**
         * 使用循环的方式判断一个元素是否存在于一个数组中
         * @param {Object} arr 数组
         * @param {Object} value 元素值
         */
        function isInArray(arr,value){
            for(var i = 0; i < arr.length; i++){
                if(value === arr[i]){
                    return true;
                }
            }
            return false;
        }

        $('.multiselect').multiselect({
            enableClickableOptGroups: true,
            enableCollapsibleOptGroups: true,
            includeSelectAllOption: true,
            buttonWidth: '225px',
            dropRight: true,
            maxHeight: 200,
            onChange: function(option, checked) {

            },
            nonSelectedText: '请选择项目',
            numberDisplayed: 10,
            enableFiltering: true,
            allSelectedText:'所有',
        });

    });

    //初始化表单验证
    function initCheck() {
        $('#defaultForm')
            .bootstrapValidator({
                message: 'This value is not valid',
                feedbackIcons: {
                    valid: 'glyphicon glyphicon-ok',
                    invalid: 'glyphicon glyphicon-remove',
                    validating: 'glyphicon glyphicon-refresh'
                },
                fields: {
                    name: {
                        message: '不是有效的用户名',
                        validators: {
                            notEmpty: {
                                message: '用户名不能为空'
                            },
                            stringLength: {
                                min: 1,
                                max: 30,
                                message: '用户名不能超过30个字符'
                            }
                            /*remote: {
                             url: 'remote.php',
                             message: 'The username is not available'
                             },*/
                            // regexp: {
                            //     regexp: /^[a-zA-Z0-9_\.]+$/,
                            //     message: ''
                            // }
                        }
                    },
                    email: {
                        validators: {
                            notEmpty: {
                                message: '邮箱不能为空'
                            },
                            emailAddress: {
                                message: '不是标准的邮箱地址'
                            }
                        }
                    },
                    identity: {
                        validators: {
                            notEmpty: {
                                message: '身份不能为空'
                            }
                        }
                    },
                    password: {
                        validators: {
                            notEmpty: {
                                message: '密码不能为空'
                            }
                        }
                    },
                    checkPassword: {
                        validators: {
                            notEmpty: {
                                message: '确认密码不能为空'
                            }
                        }
                    },
                    code: {
                        validators: {
                            notEmpty: {
                                message: 'CODE不能为空'
                            },
                            regexp: {
                                regexp: /^[0-9]+$/,
                                message: '必须为数字'
                            }
                        }
                    },
                    object:{
                        validators: {
                            notEmpty: {
                                message: '权限内项目不能为空'
                            }
                        }
                    }
                }
            })
            .on('success.form.bv', function(e) {
                // 阻止默认提交事件
                e.preventDefault();

                // 获取form表单
                var $form = $(e.target);

                // Get the BootstrapValidator instance
                var bv = $form.data('bootstrapValidator');
                console.log($('#defaultForm').serialize());

                var password=$("input[name='password']").val().trim();
                var checkPassword=$("input[name='checkPassword']").val().trim();
                if(password!=checkPassword){
                    alert("请确认密码一致");
                    return;
                }

                $.ajax({
                    url: $form.attr('action'),
                    type:"post",
                    data:$form.serialize(),
                    dataType:'json',
                    success:function (result) {
                        if(result.type == "alert"){
                            alert(result.message);
                        }
                        $("#modal").modal("hide");
                        //刷新跳转至第一页
                        // $("#dataTable").bootstrapTable("selectPage",1).bootstrapTable("refresh");
                        $("#dataTable").bootstrapTable("selectPage",1);
                    },
                    error:function () {
                        console.log("error")
                    }
                });
                // $.post($form.attr('action'), $form.serialize(), function(result) {
                //     console.log(result);
                // }, 'text');
            });
    }

</script>